<template>
	<el-container>
		<el-aside width="220px">
			<el-tree ref="category" @node-click="handleNodeClick" class="menu" node-key="label" :data="category"
					 :default-expanded-keys="['系统日志']" current-node-key="系统日志" :highlight-current="true"
					 :expand-on-click-node="false">
			</el-tree>
		</el-aside>
		<el-container>
			<el-main class="nopadding">
				<el-container>
					<el-header :height="headerHeight" style="display:block">
						<el-row :gutter="20">
							<el-col :span="24">
								<el-form :inline="true" class="content-input-length" label-width="68px">
									<el-form-item label="请求接口">
										<el-input v-model="tablesSearch.url" placeholder="请求接口" clearable/>
									</el-form-item>
									<el-form-item label="业务名称">
										<el-input v-model="tablesSearch.description" placeholder="业务名称" clearable/>
									</el-form-item>
									<el-form-item label="操作账户">
										<el-input v-model="tablesSearch.operatingAccount" placeholder="操作账户"
												  clearable/>
									</el-form-item>
									<el-form-item label="客户端IP">
										<el-input v-model="tablesSearch.clientIp" placeholder="客户端IP" clearable/>
									</el-form-item>
									<el-form-item label="操作日期" style="width: 470px">
										<el-date-picker
											v-model="tablesSearch.createTime"
											:clearable="false"
											type="datetimerange"
											range-separator="至"
											start-placeholder="开始日期"
											end-placeholder="结束日期">
										</el-date-picker>
										<span
											style="padding-left: 45px;position: absolute; top: -1.5px;left: 400px;width: 150px">
												<el-button type="primary" icon="el-icon-search"
														   @click="upsearch"></el-button>
												<el-button icon="el-icon-refresh" @click="searchReset"></el-button>
											</span>
									</el-form-item>

								</el-form>
							</el-col>
						</el-row>
					</el-header>
					<el-header style="height:150px;">
						<scEcharts height="100%" :option="logsChartOption"></scEcharts>
					</el-header>
					<el-main class="nopadding">
						<scTable ref="table" :apiObj="apiObj" :hideImport="true"
								 :hideExport="!this.$TOOL.auth.verification(['log:export'])"
								 :exportFun="batch_export"
								 stripe highlightCurrentRow @row-click="rowClick">
							<el-table-column label="级别" prop="level" width="60" align="center">
								<template #default="scope">
									<el-icon v-if="scope.row.level=='error'" style="color: #F56C6C;">
										<el-tooltip content="error级别" placement="top">
											<el-icon-circle-close-filled/>
										</el-tooltip>
									</el-icon>
									<el-icon v-if="scope.row.level=='warn'" style="color: #E6A23C;">
										<el-tooltip content="warn级别" placement="top">
											<el-icon-warning-filled/>
										</el-tooltip>
									</el-icon>
									<el-icon v-if="scope.row.level=='info'" style="color: #409EFF;">
										<el-tooltip content="info级别" placement="top">
											<el-icon-info-filled/>
										</el-tooltip>
									</el-icon>
								</template>
							</el-table-column>
							<el-table-column label="操作时间" prop="createTime" width="164"></el-table-column>
							<el-table-column label="日志ID" prop="operateLogId" width="180"></el-table-column>
							<el-table-column label="业务名称" prop="description" width="150"></el-table-column>
							<el-table-column label="请求接口" prop="url" width="270"></el-table-column>
							<el-table-column label="请求方法" prop="requestType" width="130"></el-table-column>
							<el-table-column label="操作账户" prop="operatingAccount" width="130"></el-table-column>
							<el-table-column label="客户端IP" prop="clientIp" width="130"></el-table-column>
							<el-table-column label="耗时ms" prop="consumingTime" width="90"></el-table-column>
						</scTable>
					</el-main>
				</el-container>
			</el-main>
		</el-container>
	</el-container>

	<el-drawer v-model="infoDrawer" title="日志详情" :size="600" destroy-on-close>
		<info ref="info"></info>
	</el-drawer>
</template>

<script>
import info from './info'
import scEcharts from '@/components/scEcharts'

export default {
	name: 'log',
	components: {
		info,
		scEcharts
	},
	data() {
		return {
			headerHeight: "0px",
			infoDrawer: false,
			logsChartOption: {
				color: ['#409eff', '#e6a23c', '#f56c6c'],
				grid: {
					top: '0px',
					left: '10px',
					right: '26px',
					bottom: '0px'
				},
				tooltip: {
					trigger: 'axis'
				},
				xAxis: {
					type: 'category',
					boundaryGap: false,
					data: ['2021-07-01', '2021-07-02', '2021-07-03', '2021-07-04', '2021-07-05', '2021-07-06', '2021-07-07', '2021-07-08', '2021-07-09', '2021-07-10', '2021-07-11', '2021-07-12', '2021-07-13', '2021-07-14', '2021-07-15']
				},
				yAxis: {
					show: false,
					type: 'value'
				},
				series: [
					{
						data: [],
						// data: [120, 200, 150, 80, 70, 110, 130, 120, 200, 150, 80, 70, 110, 130, 70, 110],
						type: 'bar',
						stack: 'log',
						barWidth: '15px'
					},
					{
						data: [],
						// data: [15, 26, 7, 12, 13, 9, 21, 15, 26, 7, 12, 13, 9, 21, 12, 3],
						type: 'bar',
						stack: 'log',
						barWidth: '15px'
					},
					{
						data: [],
						// data: [0, 0, 0, 120, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
						type: 'bar',
						stack: 'log',
						barWidth: '15px'
					}]
			},
			category: [
				{
					label: '系统日志',
					children: [
						{label: '全部'},
						{label: 'info'},
						{label: 'warn'},
						{label: 'error'}
					]
				},
				{
					label: '应用日志',
					children: [
						{label: 'selfHelp'},
						{label: 'WechatApp'}
					]
				}
			],
			tablesSearch: {
				createTime: this.getTimeRange(),
				clientIp: "",
				description: "",
				operatingAccount: "",
				requestType: "",
				url: "",
			},
			apiObj: this.$API.system.log.list,
			search: {
				keyword: ""
			}
		}
	},
	created() {
		window.onresize = () => {
			return (() => {
				// 监听浏览器宽高变化
				this.headerHeight = this.$TOOL.page.updateHeight();
			})()
		}
	},
	mounted() {
		// 菜单页面中 <el-header :height="headerHeight">...</el-header> 头部查询条件和新增编辑按钮区域高度
		this.headerHeight = this.$TOOL.page.updateHeight(8);
		this.upEcharData()
	},
	methods: {
		/**
		 * 搜索条件重置
		 */
		async searchReset() {
			this.tablesSearch = {
				url: "",
				description: "",
				operatingAccount: "",
				clientIp: "",
				createTime: this.getTimeRange()
			};
			this.upsearch();
		},

		async upEcharData() {
			if (!this.tablesSearch.createTime) {
				this.tablesSearch.createTime = this.getTimeRange()
			}
			let requestParams = Object.assign({}, this.tablesSearch);
			if ((typeof requestParams.createTime) != "string") {
				let startTime = this.getYearMethodDay(requestParams.createTime[0]);
				let endTime = this.getYearMethodDay(requestParams.createTime[1]);
				requestParams.createTime = "";
				requestParams.startTime = startTime;
				requestParams.endTime = endTime;
				if (this.getDateSize(new Date(startTime), new Date(endTime))) {
					return
				}
			}
			let res = await this.$API.system.log.statistics.get(requestParams);
			this.logsChartOption.xAxis.data = res.data.dateTime
			this.logsChartOption.series[0].data = res.data.infos  // info
			this.logsChartOption.series[1].data = res.data.warns  // warn
			this.logsChartOption.series[2].data = res.data.errors  // error
		},

		upsearch() {
			if (!this.tablesSearch.createTime) {
				this.tablesSearch.createTime = this.getTimeRange()
			}
			let requestParams = Object.assign({}, this.tablesSearch);
			if ((typeof requestParams.createTime) != "string") {
				let startTime = this.getYearMethodDay(requestParams.createTime[0]);
				let endTime = this.getYearMethodDay(requestParams.createTime[1]);
				requestParams.createTime = "";
				requestParams.startTime = startTime;
				requestParams.endTime = endTime;
				if (this.getDateSize(new Date(startTime), new Date(endTime))) {
					this.$message.warning('"操作时间"跨度不可超过一个月')
					return
				}
			}
			this.$refs.table.upData(requestParams)
			this.upEcharData()
		},

		handleNodeClick(data) {
			switch (data.label) {
				case 'info':
					this.tablesSearch.level = 'info';
					break;
				case 'warn':
					this.tablesSearch.level = 'warn';
					break;
				case 'error':
					this.tablesSearch.level = 'error';
					break;
				case '全部':
					this.tablesSearch.level = '';
					break;
				default:
					return
			}
			this.upsearch()
		},

		rowClick(row) {
			this.infoDrawer = true
			this.$nextTick(() => {
				this.$refs.info.setData(row)
			})
		},

		/**
		 * 批量导出
		 * @returns {Promise<void>}
		 */
		async batch_export() {
			if (!this.tablesSearch.createTime) {
				this.tablesSearch.createTime = this.getTimeRange()
			}
			let requestParams = Object.assign({}, this.tablesSearch);
			if ((typeof requestParams.createTime) != "string") {
				let startTime = this.getYearMethodDay(requestParams.createTime[0]);
				let endTime = this.getYearMethodDay(requestParams.createTime[1]);
				requestParams.createTime = "";
				requestParams.startTime = startTime;
				requestParams.endTime = endTime;
				if (this.getDateSize(new Date(startTime), new Date(endTime))) {
					this.$message.warning('"操作时间"跨度不可超过一个月')
				}
			}

			let res = await this.$API.system.log.exportList.get(requestParams);
			if (res.status == 200) {
				this.$message.success("系统数据生成中...")
			}
		},

		getYearMethodDay(date) {
			//方法里面可以分为行参、实参
			if (date == undefined) {
				date = new Date();
			}
			let nian = date.getFullYear();
			let yue = parseInt(date.getMonth()) + 1;
			let ri = date.getDate();
			var hour = date.getHours(); // 时
			var minutes = date.getMinutes(); // 分
			var seconds = date.getSeconds() //秒

			if (yue >= 1 && yue <= 9) {
				yue = "0" + yue;
			}
			if (ri >= 0 && ri <= 9) {
				ri = "0" + ri;
			}
			if (hour >= 0 && hour <= 9) {
				hour = "0" + hour;
			}
			if (minutes >= 0 && minutes <= 9) {
				minutes = "0" + minutes;
			}
			if (seconds >= 0 && seconds <= 9) {
				seconds = "0" + seconds;
			}
			let jia = nian + "-" + yue + "-" + ri + " " + hour + ":" + minutes + ":" + seconds
			return jia;
		},

		getTimeRange() {
			var endTime = new Date();
			var startTime = new Date(new Date().setDate(endTime.getDate() - 14))
			return [startTime, endTime]
		},

		getDateSize(startDate, endDate) {
			var sDate = new Date(startDate);
			var eDate = new Date(endDate);

			if (eDate.getFullYear() - sDate.getFullYear() > 1) {//先比较年
				return true;
			} else if (eDate.getMonth() - sDate.getMonth() > 1) {//再比较月
				return true;
			} else if (eDate.getMonth() - sDate.getMonth() == 1) {
				if (eDate.getDate() - sDate.getDate() >= 1) {
					return true;
				}
			} else if (eDate.getFullYear() - sDate.getFullYear() == 1) {
				if (eDate.getMonth() + 12 - sDate.getMonth() > 1) {
					return true;
				} else if (eDate.getDate() - sDate.getDate() >= 1) {
					return true;
				}
			}
			return false;
		}

	}
}
</script>

<style>
</style>
